import streamlit as st
from importlib.machinery import SourceFileLoader
import os

# 加载 app.py 和 Final.py 模块
app = SourceFileLoader("app", os.path.join(os.getcwd(), "DataViz.py")).load_module()
final = SourceFileLoader("Final", os.path.join(os.getcwd(), "ChatBot.py")).load_module()

# 假数据库文件路径
DB_FILE = "users.txt"

# 读取用户数据
def read_users():
    if not os.path.exists(DB_FILE):
        return {}
    with open(DB_FILE, "r") as f:
        users = {}
        for line in f:
            username, password = line.strip().split(",")
            users[username] = password
        return users

# 写入用户数据
def write_users(users):
    with open(DB_FILE, "w") as f:
        for username, password in users.items():
            f.write(f"{username},{password}\n")

# 注册功能
def register():
    col1, col2, col3 = st.columns([1, 2, 1])

    with col2:
        st.markdown("""
            <div style="text-align:center; margin-bottom:2rem;">
                <h2 style="color:#1E40AF; font-weight:600;">招聘数据分析系统</h2>
                <p style="color:#64748B;">创建新账户</p>
            </div>
        """, unsafe_allow_html=True)

        # 创建卡片效果
        with st.container():
            new_username = st.text_input(
                "新用户名",
                key="register_username",
                placeholder="请输入新用户名",
                label_visibility="collapsed"
            )

            new_password = st.text_input(
                "新密码",
                type="password",
                key="register_password",
                placeholder="请输入新密码",
                label_visibility="collapsed"
            )

            confirm_password = st.text_input(
                "确认密码",
                type="password",
                key="confirm_password",
                placeholder="请再次输入密码",
                label_visibility="collapsed"
            )

            # 美化按钮
            col_button, = st.columns([1])
            with col_button:
                if st.button("注册", use_container_width=True):
                    if not new_username or not new_password:
                        st.error("用户名和密码不能为空", icon="🚫")
                    elif new_password != confirm_password:
                        st.error("两次输入的密码不一致", icon="🚫")
                    else:
                        users = read_users()
                        if new_username in users:
                            st.error("该用户名已存在，请选择其他用户名", icon="🚫")
                        else:
                            users[new_username] = new_password
                            write_users(users)
                            st.success("注册成功，请使用新账户登录", icon="✅")
                            st.session_state.show_register = False
                            st.rerun()

            st.markdown("</div>", unsafe_allow_html=True)

        # 添加底部链接
        st.markdown("""
            <div style="text-align:center; margin-top:1.5rem;">
                <span style="color:#64748B;">已有账户? </span>
                <button onclick="document.getElementById('login_button').click();" 
                        style="background:none; border:none; color:#1E40AF; text-decoration:underline; cursor:pointer;">
                    返回登录
                </button>
            </div>
            <script>
                // 创建一个隐藏的登录按钮用于JS触发
                document.addEventListener('DOMContentLoaded', function() {
                    const loginButton = document.createElement('button');
                    loginButton.id = 'login_button';
                    loginButton.style.display = 'none';
                    loginButton.onclick = function() {
                        document.querySelector('[data-testid="stButton"][aria-label="登录"] button').click();
                    };
                    document.body.appendChild(loginButton);
                });
            </script>
        """, unsafe_allow_html=True)

# 登录功能
def login():
    col1, col2, col3 = st.columns([1, 2, 1])

    with col2:
        st.markdown("""
            <div style="text-align:center; margin-bottom:2rem;">
                <h2 style="color:#1E40AF; font-weight:600;">招聘数据分析系统</h2>
                <p style="color:#64748B;">登录您的账户</p>
            </div>
        """, unsafe_allow_html=True)

        # 创建卡片效果
        with st.container():
            username = st.text_input(
                "用户名",
                key="login_username",
                placeholder="请输入用户名",
                label_visibility="collapsed"
            )

            password = st.text_input(
                "密码",
                type="password",
                key="login_password",
                placeholder="请输入密码",
                label_visibility="collapsed"
            )

            # 美化按钮
            col_button, = st.columns([1])
            with col_button:
                if st.button("登录", use_container_width=True):
                    users = read_users()
                    if username in users and users[username] == password:
                        st.session_state.logged_in = True
                        st.session_state.page = "数据分析应用"  # 默认进入数据分析应用
                        st.rerun()
                    else:
                        st.error("用户名或密码错误", icon="🚫")

            col_register, = st.columns([1])
            with col_register:
                if st.button("注册", use_container_width=True):
                    st.session_state.show_register = True

            st.markdown("</div>", unsafe_allow_html=True)

# 侧边栏导航（仅保留注销按钮，删除菜单切换功能）
def setup_sidebar():
    st.sidebar.header("导航菜单")
    if st.sidebar.button("注销", key="logout_button"):
        st.session_state.logged_in = False
        st.session_state.page = None
        st.rerun()

# 顶部固定切换按钮（带圆角和粘性定位）
def setup_top_buttons():
    # 固定定位CSS（带圆角矩形）
    st.markdown("""
    <style>
        .top-buttons {
            position: sticky; /* 粘性定位 */
            top: 0; /* 固定在顶部 */
            background-color: white;
            padding: 12px 0;
            border-bottom: 2px solid #e0e0e0;
            z-index: 1000;
        }
        .button-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px; /* 按钮间距 */
            padding: 0 24px; /* 容器内边距 */
        }
        .stButton>button {
            width: 100%!important;
            padding: 14px 0!important;
            font-size: 16px!important;
            background-color: #f8f9fa!important;
            color: #333!important;
            border: none!important;
            border-radius: 24px!important; /* 圆角矩形 */
            box-shadow: 0 2px 8px rgba(0,0,0,0.05)!important; /* 阴影效果 */
            transition: all 0.2s ease!important; /* 过渡动画 */
        }
        .stButton>button:hover {
            background-color: #e9ecef!important;
            transform: translateY(-1px)!important; /* 悬停时轻微上移 */
        }
        .stButton>button:focus,
        .stButton>button:active {
            background-color: #1E40AF!important;
            color: white!important;
            box-shadow: 0 4px 12px rgba(30, 64, 175, 0.2)!important; /* 选中时加深阴影 */
        }
        /* 修复内容被遮挡问题 */
        .main-content {
            margin-top: 68px!important; /* 根据按钮高度调整 */
        }
    </style>
    """, unsafe_allow_html=True)
    
    # 创建按钮容器
    st.markdown('<div class="top-buttons">', unsafe_allow_html=True)
    
    col1, col2 = st.columns(2)
    with col1:
        if st.button("数据分析应用", 
                    key="app_btn", 
                    type="primary" if st.session_state.page == "数据分析应用" else "secondary"):
            st.session_state.page = "数据分析应用"
            st.rerun()
    
    with col2:
        if st.button("AI 对话助手应用", 
                    key="final_btn", 
                    type="primary" if st.session_state.page == "AI 对话助手应用" else "secondary"):
            st.session_state.page = "AI 对话助手应用"
            st.rerun()
    
    st.markdown('</div>', unsafe_allow_html=True)

# 主函数
def main():
    # 初始化会话状态
    if 'logged_in' not in st.session_state:
        st.session_state.logged_in = False
    if 'page' not in st.session_state:
        st.session_state.page = "数据分析应用"  # 默认页面
    if 'show_register' not in st.session_state:
        st.session_state.show_register = False

    if st.session_state.show_register:
        register()
    elif not st.session_state.logged_in:
        login()
    else:
        setup_sidebar()        # 侧边栏（仅注销）
        setup_top_buttons()    # 顶部切换按钮

        # 创建内容容器（避免被固定按钮遮挡）
        st.markdown('<div class="main-content">', unsafe_allow_html=True)
        
        # 状态保存与页面加载
        if st.session_state.page == "数据分析应用":
            # 保存AI助手状态
            if hasattr(st.session_state, 'final_state'):
                st.session_state.final_state = {
                    "messages": st.session_state.get("final_messages", []),
                    "api_key": st.session_state.get("final_api_key", ""),
                    "temperature": st.session_state.get("final_temperature", 0.6)
                }
            app.main()
        elif st.session_state.page == "AI 对话助手应用":
            # 保存数据分析状态
            if hasattr(st.session_state, 'app_state'):
                st.session_state.app_state = {
                    "cities": st.session_state.get("app_cities", []),
                    "educations": st.session_state.get("app_educations", []),
                    "companies": st.session_state.get("app_companies", []),
                    "positions": st.session_state.get("app_positions", []),
                    "min_salary": st.session_state.get("app_min_salary", 0),
                    "max_salary": st.session_state.get("app_max_salary", 100000)
                }
            final.main(
                api_key=st.session_state.get("final_api_key", ""),
                temperature=st.session_state.get("final_temperature", 0.6),
                messages=st.session_state.get("final_messages", [])
            )
            
        st.markdown('</div>', unsafe_allow_html=True)

if __name__ == "__main__":
    main()